//
//  AppDelegate.m
//  WBBaseProject
//
//  Created by 吴斌 on 2017/6/26.
//  Copyright © 2017年 吴斌. All rights reserved.
//

#import "AppDelegate.h"
#import "AppDelegate+Category.h"
#import "SNLocationManager.h"
#import "KLTNavigationController.h"
#import <IQKeyboardManager.h>

#import "GestureViewController.h"
#import "PCCircleViewConst.h"

#import <UMSocialCore/UMSocialCore.h>
#import "JPUSHService.h"

// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

#define JpushAppKey @""
#define JpushSecret @""

#define UMshareAppKey @""

#define QQAppID @""
#define QQAppKey @""

#define WXAppKey @""
#define WXAppSecret @""

@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self setRegisterPwd];
    
    /*! 创建tabBar */
//    [self wb_createTabbar];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.tabBarController = [[TabbarViewController alloc] init];
    self.window.rootViewController = self.tabBarController;
    [self.window makeKeyAndVisible];
    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"NavigationBg"] forBarMetrics:0];
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17],NSForegroundColorAttributeName:[UIColor whiteColor]}];
  
    
    /*! 设置statusBar为白色 注意plist中的View controller-based status bar appearance设为NO*/
    [WB_SharedApplication setStatusBarStyle:UIStatusBarStyleLightContent];;
   
    /*! 开启网络监测 */
//    [self wb_networkActivityIndicator];
 
    if (@available(iOS 11.0,*)) {
        [UIScrollView appearance].contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    //获取定位
    [self getLocation];
    
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = 60;
    
//    //jpush
//    [self startJpush:launchOptions];
//    
//    //友盟
//    [self startUM];
    
    return YES;
}

- (void)getLocation
{
    [[SNLocationManager shareLocationManager] startUpdatingLocationWithSuccess:^(CLLocation *location, CLPlacemark *placemark) {
        NSString *address = @"";
        if ([placemark.addressDictionary[@"FormattedAddressLines"] count]) {
            address = placemark.addressDictionary[@"FormattedAddressLines"][0];
        }
        
        double latitude = location.coordinate.latitude;
        double longitude = location.coordinate.longitude;
        NSString *latitudeStr = [NSString stringWithFormat:@"%f",latitude];
        NSString *longitudeStr = [NSString stringWithFormat:@"%f",longitude];
        
        NSString *city = placemark.locality;
        if (!city) {
            //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
            city = placemark.administrativeArea;
        }        
        
        NSDictionary *resultDic = [NSDictionary dictionaryWithObjectsAndKeys:placemark.subLocality,@"districts",latitudeStr, @"latitudes",longitudeStr,@"longitudes",address,@"detailAddress",placemark.addressDictionary[@"State"],@"provinces",city,@"citys",nil];
        DebugLog(@"%@",resultDic);
        [[NSUserDefaults standardUserDefaults] setObject:resultDic forKey:LocationInfo];
        
    } andFailure:^(CLRegion *region, NSError *error) {
        DebugLog(@"获取定位失败");
    }];
}
    

- (void)startJpush:(NSDictionary *)launchOptions
{
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    [JPUSHService setupWithOption:launchOptions
                           appKey:JpushAppKey
                          channel:@""
                 apsForProduction:NO];
}
- (void)startUM
{
    /* 打开调试日志 */
    [[UMSocialManager defaultManager] openLog:YES];
    
    /* 设置友盟appkey */
    [[UMSocialManager defaultManager] setUmSocialAppkey:UMshareAppKey];
    
    //初始化平台
    [self configUSharePlatforms];
}
- (void)configUSharePlatforms
{
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:WXAppKey appSecret:WXAppSecret redirectURL:@"http://mobile.umeng.com/social"];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:QQAppID/*设置QQ平台的appID*/  appSecret:QQAppKey redirectURL:@"http://mobile.umeng.com/social"];
}


- (void)applicationWillResignActive:(UIApplication *)application {
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
}


- (void)applicationWillEnterForeground:(UIApplication *)application{
   
}


- (void)setRegisterPwd
{
    //是否设置手势验证码
    NSString *GesturepassWord = [PCCircleViewConst getGestureWithKey:gestureFinalSaveKey];
    if (!WB_IsNilString(GesturepassWord)) {
        GestureViewController *vc = [[GestureViewController alloc] init];
        [vc setType:GestureViewControllerTypeLogin];
        KLTNavigationController *navi = [[KLTNavigationController alloc] initWithRootViewController:vc];
        [self.window.rootViewController presentViewController:navi animated:NO completion:nil];
    }
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    [self setRegisterPwd];
}


- (void)applicationWillTerminate:(UIApplication *)application{
}
#pragma mark JpushDelegate
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

@end
